package com.chatmusicstatus;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import android.text.InputType;
import com.chatmusicstatus.accounts.addAdv;
import com.chatmusicstatus.accounts.AccountSQLiteHelper;
import com.chatmusicstatus.accounts.ModifyAcc;
import com.chatmusicstatus.service.MusicStatusService;

public class MainActivity extends PreferenceActivity
{
    //PreferenceActivity self = this;     //need to figure out better work around
    PreferenceCategory existing_accounts;
    int isRunning;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.main);
        
        existing_accounts = (PreferenceCategory) findPreference("existing_accounts");
        existing_accounts.setOrderingAsAdded(true);
        LoadAccounts();
        
        final Preference status = (Preference) findPreference("status");
        if(isMusicServiceRunning())
        {
            status.setTitle("Service Status: Active");
            isRunning=1;
        }
        else
        {
            status.setTitle("Service Status: Inactive");
            isRunning=0;
        }
        
        Preference toggle = (Preference) findPreference("toggle");
        toggle.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                if(isMusicServiceRunning()){
                    stopService(new Intent(MainActivity.this, MusicStatusService.class));
                    status.setTitle("Service Status: Inactive");
                }
                else {
                    //startService(new Intent(MainActivity.this, MusicStatusService.class));
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                    Intent intent;
                    if(prefs.getBoolean("is_persistent", true))
                        intent = new Intent(MusicStatusService.ACTION_FOREGROUND);
                    else
                        intent = new Intent(MusicStatusService.ACTION_BACKGROUND);
                    intent.setClass(MainActivity.this, MusicStatusService.class);
                    startService(intent);
                    status.setTitle("Service Status: Active");
                }
                return true;
                }
            });
        EditTextPreference pause_timeout= (EditTextPreference) findPreference("pause_timeout");
        pause_timeout.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
        pause_timeout.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

            public boolean onPreferenceChange(Preference prfrnc, Object o) {
                try
                {
                    Integer.parseInt(o.toString());
                    return true;
                }
                catch(NumberFormatException ex)
                {
                    return false;
                }
            }
        });
        CheckBoxPreference usertune = (CheckBoxPreference) findPreference("usertune");
        Preference setmessage = (Preference) findPreference("setmessage");
                if(usertune.isChecked())
                {
                    setmessage.setEnabled(false);
                }
                else
                {
                    setmessage.setEnabled(true);
                }
        usertune.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

            public boolean onPreferenceChange(Preference prfrnc, Object o) {
                Preference setmessage = (Preference) findPreference("setmessage");
                if((Boolean)o)
                {
                    setmessage.setEnabled(false);
                }
                else
                {
                    setmessage.setEnabled(true);
                }
                return true;
            }
        });
        Preference create_account = (Preference) findPreference("create_account");
        create_account.setOnPreferenceClickListener(new OnPreferenceClickListener() {

            public boolean onPreferenceClick(Preference prfrnc) {
                return true;
            }
        });
        Preference create_account_adv = (Preference) findPreference("create_account_adv");
        create_account_adv.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            
            public boolean onPreferenceClick(Preference prfrnc) {
                startActivityForResult(new Intent(MainActivity.this,addAdv.class), 0);
                return true;
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==1)
        {
            //something was added to DB, reload page
            //startActivity(getIntent());
            //finish();
            LoadAccounts();
        }
    }

    private void LoadAccounts() {
        existing_accounts.removeAll();
        AccountSQLiteHelper accHelper = new AccountSQLiteHelper(this);
        SQLiteDatabase db = accHelper.getReadableDatabase();
        final Cursor cursor = db.query(AccountSQLiteHelper.TABLE, AccountSQLiteHelper.ACCOUNTDISP, null, null, null, null, null);
        startManagingCursor(cursor);
        Preference pref;
        while (cursor.moveToNext()) {
            pref = new Preference(this);
            pref.setKey("account_"+Integer.toString(cursor.getInt(0)));
            pref.setPersistent(false);
            pref.setTitle(cursor.getString(1));
            if(cursor.getInt(2)==1)
                pref.setSummary("Active");
            else
                pref.setSummary("Inactive");
            pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                final int acc_id = cursor.getInt(0);
                public boolean onPreferenceClick(Preference prfrnc) {
                    Intent i = new Intent(MainActivity.this, ModifyAcc.class);
                    i.putExtra("acc_id", acc_id);
                    startActivityForResult(i, 0);
                    return true;
                }
            });
            existing_accounts.addPreference(pref);
        }
        cursor.close();
    }
    private boolean isMusicServiceRunning() 
    {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) 
        {
            if ("com.chatmusicstatus.service.MusicStatusService".equals(service.service.getClassName()))
            {
                return true;
            }
        }
        return false;
    }
}